<template>
	<view>
		<canvas style="width: 305px; height: 435px; background-color: #fff; border: 1px solid #eee; border-radius: 15rpx;overflow: hidden;"
		 canvas-id="shareCanvas" id="shareCanvas"></canvas>
	</view>
</template>

<script>
	export default {
		props: {
			canvasInfo: {
				type: Object,
				default () {
					return {
						curBannerUrl: '',
						codeUrl: '',
						avatar: '',
						name: '去嗨鸭',
						desc1: '邀您一起加入',
						desc2: '去嗨鸭',
					}
				}
			}
		},
		data() {
			return {

			};
		},
		onReady() {
			uni.showToast({
				title: '生成中...',
				icon: 'loading'
			})
			this.initCanvas()
		},
		methods: {
			/*初始化画布*/
			initCanvas() {
				const ctx = uni.createCanvasContext('shareCanvas', this)
				let str, str1 = '',
					length = 12,
					isLength = false;
				if (this.canvasInfo.name.length > length) {
					isLength = true
					str = this.canvasInfo.name.substring(0, length)
					str1 = this.canvasInfo.name.substring(length)
				} else {
					str = this.canvasInfo.name
				}
				ctx.setFillStyle('#ffffff')
				ctx.fillRect(0, 0, 305, 435)
				ctx.draw()

				ctx.drawImage(this.canvasInfo.curBannerUrl, 0, 0, 305, 330)
				ctx.drawImage(this.canvasInfo.codeUrl, 232, 355, 50, 50)

				ctx.setFontSize(14)
				ctx.setFillStyle('#000000')
				ctx.fillText(str, 70, 372)
				if (isLength) {
					ctx.fillText(str1, 70, 392)
				}

				ctx.setFontSize(12)
				ctx.setFillStyle('#999999')
				if (!isLength) {
					ctx.fillText(this.canvasInfo.desc1, 70, 392)
					ctx.fillText(this.canvasInfo.desc2, 70, 412)
				} else {
					ctx.fillText(this.canvasInfo.desc1 + '  ' + this.canvasInfo.desc2, 70, 412)
				}

				ctx.fillText('长按识别', 232, 420)

				ctx.arc(36, 375, 22, 0, Math.PI * 2)
				ctx.clip()
				ctx.drawImage(this.canvasInfo.avatar, 14, 363, 44, 44)


				ctx.draw(true, () => {
					setTimeout(() => {
						this.saveImg()
					}, 500)
				})
			},
			saveImg() {
				uni.canvasToTempFilePath({
					canvasId: 'shareCanvas',
					success: (res) => {
						// 在H5平台下，tempFilePath 为 base64
						console.log(res.tempFilePath)
						uni.saveImageToPhotosAlbum({
							filePath: res.tempFilePath,
							success: () => {
								uni.showToast({
									title: '保存成功'
								})
								this.$emit('reset')
							},
							fail: () => {
								uni.showToast({
									title: '保存失败',
									icon: 'none'
								})
								this.$emit('reset')
							}
						})
					},
					fail: function(fail) {
						console.log('fail', fail);
						uni.showToast({
							title: '保存图片失败',
							icon: 'none'
						});
					}
				}, this)
			},
		}
	}
</script>

<style lang="scss" scoped>
</style>
